CREATE PROCEDURE coreCmsCheckout
(
	@cid			int,
	@OwnerID		int
)
AS
BEGIN
	SET NOCOUNT ON;

	/* Declarations */
	DECLARE	@previousVersionID		int;
	DECLARE @previousVersionNumber	int;
	DECLARE @newVersionID			int;
	DECLARE @newVersionNumber		int;
	
	/* Get the version record id */
	SELECT @previousVersionID = ISNULL(FK_VersionV, -1) FROM Content WHERE PK_ID=@cid;
	SELECT @previousVersionNumber = ISNULL(VersionNumber, 0) FROM ContentV WHERE PK_ID=@previousVersionID;
	SELECT @newVersionNumber = @previousVersionNumber + 1;
		
	/* Copy the latest record */
	INSERT INTO ContentV 
		(
			FK_ContentID, 
			VersionNumber, 
			FK_CheckedInBy, 
			CheckedInDT, 
			VersionNotes, 
			XMLData
		)
		SELECT 
			FK_ContentID, 
			@newVersionNumber,
			-1, GETDATE(), '', 
			XMLData
		FROM ContentV WHERE PK_ID=@previousVersionID;
	
	SELECT @newVersionID = @@IDENTITY;		
	
	/* Update the records */
	UPDATE Content SET
		WorkflowStatus = 0,
		FK_CheckedOutTo = @OwnerID,
		CheckedOutDT = GETDATE(),
		CurrentVersionNumber = @newVersionNumber,
		FK_VersionV = @newVersionID
	WHERE PK_ID=@cid;

	SET NOCOUNT OFF;	
END